Bokeh Mic Check

Original Widget+Bokeh 0.9 integration kwharrigan.


In [1]:
import time
import threading

import numpy as np

import pyaudio

from ipywidgets import Button
from IPython import display

from bokeh.plotting import figure, show, ColumnDataSource
from bokeh.io import push_notebook, output_notebook

In [2]:
output_notebook()


Loading BokehJS ...

Configuration Options for PyAudio

You'll almost certainly have to hack these for your specific hardware. There will be kernel crashes.


In [3]:
FORMAT = pyaudio.paInt16 
CHANNELS = 2
RATE = 44100 / 2
INPUT_BLOCK_TIME = 0.05
INPUT_FRAMES_PER_BLOCK = int(RATE * INPUT_BLOCK_TIME)
DEVICE_INDEX = 0
FRAMES_PER_BUFFER = 512

In [4]:
class MicThread(threading.Thread):
    def run(self):
        self.stream = pyaudio.PyAudio().open(
            format=FORMAT,
            rate=RATE,
            channels=CHANNELS,
            input_device_index=DEVICE_INDEX,
            input=True,
            output=False,
            frames_per_buffer=FRAMES_PER_BUFFER
        )
        self.running = True
        while self.running:
            data_source.data.update(y=self.read())
            push_notebook(handle=handle)
            time.sleep(0.0025)
        self.stream.close()
    
    def read(self):
        return np.frombuffer(
            self.stream.read(
                INPUT_FRAMES_PER_BLOCK,
                exception_on_overflow=False),
            np.short)
            
    def stop(self):
        self.running = False

In [5]:
start_button = Button(
    description=' Start',
    font_family="Noto Sans",
    font_size="5rem",
    button_style="primary",
    icon="fa-microphone",
    width="100%")

@start_button.on_click
def start(btn):
    if btn.description == " Start":
        t = MicThread()
        t.start()
        setattr(btn, "_thread", t)
        btn.description = " Stop"
        btn.icon = "fa-microphone-slash"
        btn.button_style = "danger"
    else:        
        btn._thread.stop()
        btn.description = " Start"
        btn.icon = "fa-microphone"
        btn.button_style = "primary"

start_button

In [6]:
data_source = ColumnDataSource(dict(x=range(1000), y=range(1000)))
p = figure(plot_width=1300,
           plot_height=625,
           x_range=[0, 1000],
           y_range=[-10000, 10000])
p.line("x", "y", source=data_source)
handle = show(p)



In [ ]: